package world.ztomorrow.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import world.ztomorrow.common.constant.SystemConstant;
import world.ztomorrow.common.dto.RestResp;
import world.ztomorrow.common.exception.BusinessException;
import world.ztomorrow.gateway.auth.AuthStrategy;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

import static world.ztomorrow.common.constant.SystemConstant.VISIT_URL;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthStrategy authStrategy;
    private final ObjectMapper objectMapper;
    private static final List<String> NOT_AUTH_URI = List.of(
            "/front/search/**",
            "/front/home/**", "/front/news/**", "/front/rank/**",
            "/front/book/**", "/front/resource/**",
            "/front/user/register", "/front/user/login"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 获取请求的 URI
        String requestUri = request.getPath().toString();
        PathMatcher pathMatcher = new AntPathMatcher();

        boolean match = NOT_AUTH_URI.stream().anyMatch(pattern -> pathMatcher.match(pattern, requestUri));

        if(match && !requestUri.equals(VISIT_URL)){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }

        // 获取登录 JWT
        List<String> headers = request.getHeaders().get(SystemConstant.HTTP_AUTH_HEADER_NAME);
        String token = !CollectionUtil.isEmpty(headers)? headers.get(0) : null;

        // 开始认证
        Long userId = null;
        try {
            userId = authStrategy.authSSO(token);

        } catch (BusinessException exception) {
            // 认证失败
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            response.getHeaders().setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));

            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                String responseBody = objectMapper
                        .writeValueAsString(RestResp.fail(exception.getErrorCodeEnum()));
                DataBuffer buffer = bufferFactory.wrap(responseBody.getBytes(StandardCharsets.UTF_8));
                return response.writeWith(Mono.just(buffer));
            } catch (Exception e) {
                return Mono.error(e);
            }
        }

        ServerWebExchange ex = exchange;

        if (userId != null) {
            Long finalUserId = userId;
            ex = exchange.mutate()
                    .request(i -> i.header(SystemConstant.NOVEL_FRONT_KEY, finalUserId.toString()))
                            .build();
        }

        return chain.filter(ex);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
